<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\UploadClass;
use Intervention\Image\ImageManagerStatic as Image;
use GuzzleHttp\Client;

class UploadController extends Controller
{
    /**
     *
     *@return {"data":{"url":"\/storage\/images\/20190529\/2e34be3b17d864ec3d44b118effdbbac.jpg"},"code":200,"message":"图片上传成功"}
     */
    public function uploadImg(Request $request)
	{
		$upload = new UploadClass(); 

		$upload->exts=array('jpg','png'); 

		$upload->maxSize=20*1024*1024; 
		$upload->savePath='storage/images'; 

		$file = $request->all();
        if (isset($file['_token'])){
            unset($file['_token']);
        }
		$urlArray = [];
		foreach ($file as $k => $v) {
			$originalName = $v->getClientOriginalName();
			$imgUrl = $upload->upload($v); 
			if($imgUrl) {
				$newimg = substr($imgUrl,1);
                $img = Image::make($newimg)->resize(800, 600);
                $newimgUrl = str_replace(".","_43.",$newimg);
				$img->save($newimgUrl);
				$imgArray = ['name'=>$originalName,'url'=>$imgUrl];
				$urlArray[] = $imgArray;  
				$message = '图片上传成功';
			} else {
				$message = $upload->getError();
				return response()->json(['data' => [],'code' => 200,'message' => $message], 200)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
			}
		}
		
		return response()->json(['data' => $urlArray,'code' => 200,'message' => $message], 200)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
	}

	public function uploadMp4(Request $request)
	{
		$upload = new UploadClass(); 
		$upload->exts=array('mp4'); 
		$upload->maxSize=15*1024*1024; 
		$upload->savePath='storage/mp4'; 
		$file = $request->file('mp4file'); 
		$imgUrl = $upload->upload($file); 
		if(!$imgUrl){
			$message = $upload->getError();
		} else {
			$message = '视频上传成功';
		}
		return response()->json(['data' => $imgUrl,'code' => 200,'message' => $message], 200)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
	}
    /**
     * 上传所有的文件
     *@return {"data":{"url":"\/storage\/images\/20190529\/2e34be3b17d864ec3d44b118effdbbac.jpg"},"code":200,"message":"图片上传成功"}
     */
    public function uploadAll(Request $request)
    {
        $upload = new UploadClass();
        //$upload->exts=array('jpg','png','ppt','doc','docx','xls','xlsx');
        $upload->maxSize=15*1024*1024;
        $upload->savePath='storage/all';
        $file = $request->file('file');
        $url = $upload->upload($file);
        if(!$url){
            $message = $upload->getError();
        } else {
            $message = '上传成功';
        }
        $url = 'http://'.$_SERVER['HTTP_HOST'].$url;
        return response()->json(['data' => $url,'code' => 200,'message' => $message], 200)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }
}
